package tt.dz.appserver.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import tt.dz.appserver.entity.vo.station.StationInfoVo;
import tt.dz.appserver.util.json.JsonUtils;

/**
 * 站点文件操作帮助类
 * @author xielf
 *
 */
public class StationOpUtils {

	
	/**
	 * 新建或更新站点文件数据
	 * @param provinceId
	 * @param stationName
	 * @param jsonObject
	 */
	public static void writeOrUpdateStationObject(String provinceId, String stationName, StationInfoVo stationDetailVo) {

		OutputStream outputStream = null;
		try {
			// 文件夹路径
			String dirURL = URLDecoder.decode(Constants.class.getClassLoader().getResource("tt").getPath(),
					Constants.CHARSET) +Constants.STATION_FILE+"/" + provinceId;
			// 文件夹
			File dir = new File(dirURL);
			
			// 判断是否存在
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File file = new File(dirURL + "/" + stationName + ".data");

			// 文件
			if (!file.exists()) {
				file.createNewFile();
			} else {
				file.delete();
				file.createNewFile();
			}
			outputStream = new FileOutputStream(file);
			OutputStreamWriter writer = new OutputStreamWriter(outputStream, Constants.CHARSET);
			writer.append(JSONObject.toJSONString(stationDetailVo,SerializerFeature.PrettyFormat,SerializerFeature.SortField));
			writer.flush();
			writer.close();

		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("写入【 "+stationName+" 】站点报异常");
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static final void deleteProvinceStation(String provinceId){
		
		
		OutputStream outputStream = null;
		try {
			// 文件夹路径
			String dirURL = URLDecoder.decode(Constants.class.getClassLoader().getResource("tt").getPath(),
					Constants.CHARSET) +Constants.STATION_FILE+"/" + provinceId;
			// 文件夹
			File dir = new File(dirURL);
			// 判断是否存在
			if (dir.exists()) {
				clearDir(dir);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 读取所有站点file
	 * 
	 * @return
	 * @throws IOException 
	 */
	public static List<StationInfoVo> readStationObject() throws IOException {

		List<StationInfoVo> stationDetailVos = new ArrayList<StationInfoVo>();
		
		BufferedReader reader = null;
		FileInputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		
		try {
			String dirURL = URLDecoder.decode(Constants.class.getClassLoader().getResource("tt").getPath(),
					Constants.CHARSET) + Constants.STATION_FILE;
			// 文件夹
			File dir = new File(dirURL);
			// 判断是否存在
			if (!dir.exists()) {
				throw new FileNotFoundException("站点数据文件不存在");
			}
			else{
				
				//获取所有的省份目录
				File[] dirFiles = dir.listFiles();
				
				//循环省份目录
				for (File childDir : dirFiles) {
					
					if(childDir.isDirectory()){
						//获取文件夹所有的数据文件
						File[] files = childDir.listFiles();
						
						//遍历文件
						for (File file : files) {
							
							if(file.isFile()){
								String readData = null;
								StringBuffer allStr = new StringBuffer();
								
								//流相关
								inputStream = new FileInputStream(file);
								inputStreamReader = new InputStreamReader(inputStream, Constants.CHARSET);
								reader = new BufferedReader(inputStreamReader);
								
								while((readData = reader.readLine())!=null){
									allStr.append(readData);
								}
								JSONObject stationData = JSONObject.parseObject(allStr.toString());
								StationInfoVo stationDetailVo = JsonUtils.JsonToObjectOfClass(stationData, StationInfoVo.class);
								stationDetailVos.add(stationDetailVo);

								reader.close();
								inputStreamReader.close();
								inputStream.close();
							}
						}
					}
				}
			}
		} catch (IOException e) {
			throw e;
		}
		return stationDetailVos;
	}
	
	/**
	 * 根据provinceId获取站点信息
	 * @param provinceId
	 * @return
	 */
	public static JSONArray readStationObjectByProvinceId(String provinceId) {

		JSONArray jsonArray = new JSONArray();
		
		BufferedReader reader = null;
		FileInputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		try {
			String dirURL = URLDecoder.decode(Constants.class.getClassLoader().getResource("tt").getPath(),
					Constants.CHARSET) + Constants.STATION_FILE+" /"+provinceId;
			// 文件夹
			File dir = new File(dirURL);
			// 判断是否存在
			if (!dir.exists()) {
				throw new FileNotFoundException("该省份站点数据文件不存在");
			}
			else{
				
				//获取所有省份
				if(dir.isDirectory()){
					//获取文件夹所有的数据文件
					File[] files = dir.listFiles();
					
					//遍历文件
					for (File file : files) {
						
						if(file.isFile()){
							String readData = null;
							StringBuffer allStr = new StringBuffer();
							//流相关
							inputStream = new FileInputStream(file);
							inputStreamReader = new InputStreamReader(inputStream, Constants.CHARSET);
							reader = new BufferedReader(inputStreamReader);
							
							while((readData = reader.readLine())!=null){
								allStr.append(readData);
							}
							JSONObject stationData = JSONObject.parseObject(allStr.toString());
							jsonArray.add(stationData);
							
							inputStream.close();
							inputStreamReader.close();
							reader.close();
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonArray;
	}
	
	/**
	 * 清理文件夹
	 * @param file
	 */
	public static void clearDir(File file) {
		
        if (file.isDirectory()) {  
            for (File f : file.listFiles()) {  
                clearDir(f);  
                f.delete();  
            }  
        }  
        file.delete();  
    }  
	public static void main(String[] args) {
		deleteProvinceStation("D:/310000");
	}
}
